package cn.jiangzeyin.controller.classifiers;

import cn.hutool.core.util.StrUtil;
import cn.jiangzeyin.CommonProperties;
import cn.jiangzeyin.common.JsonMessage;
import cn.jiangzeyin.common.spring.SpringUtil;

import java.io.File;

/**
 * 文本分类 base
 *
 * @author jiangzeyin
 * date 2017/12/9
 */
public abstract class BaseClassification {
    protected volatile static String corpusFolder;

    /**
     * 获取model 目录
     *
     * @return 结果数组
     */
    String[] getModelFolder() {
        String[] result = new String[2];
        String modelFolder = SpringUtil.getEnvironment().getProperty(CommonProperties.MODEL_FOLDER);
        if (StrUtil.isEmpty(modelFolder)) {
            result[0] = JsonMessage.getString(500, "please config " + CommonProperties.MODEL_FOLDER);
            return result;
        }
        File file = new File(modelFolder);
        if (!file.exists() || !file.isDirectory()) {
            result[0] = JsonMessage.getString(501, "config " + CommonProperties.MODEL_FOLDER + " not is directory or not exists");
            return result;
        }
        result[1] = modelFolder;
        return result;
    }

    /**
     * 获取分类词典目录
     *
     * @return 结果数组
     */
    private String[] getCorpusFolder() {
        String[] result = new String[2];
        String corpusFolder = SpringUtil.getEnvironment().getProperty(CommonProperties.CORPUS_FOLDER);
        if (StrUtil.isEmpty(corpusFolder)) {
            result[0] = JsonMessage.getString(500, "please config " + CommonProperties.CORPUS_FOLDER);
            return result;
        }
        File file = new File(corpusFolder);
        if (!file.exists() || !file.isDirectory()) {
            result[0] = JsonMessage.getString(501, "config " + CommonProperties.CORPUS_FOLDER + " not is directory or not exists");
            return result;
        }
        result[1] = corpusFolder;
        return result;
    }

    /**
     * 防止传入当前文件夹以上的目录
     *
     * @param path 目录
     * @return 替换掉 ..  不会先上一级目录传递
     */
    protected String replacePath(String path) {
        return path.replace("..", "");
    }

    /**
     * 处理获取分类词库库路径
     *
     * @return json tip
     */
    protected String doCorpusFolder() {
        if (StrUtil.isEmpty(corpusFolder)) {
            String[] result = getCorpusFolder();
            if (result[0] != null) {
                return result[0];
            }
            corpusFolder = result[1];
        }
        return null;
    }
}
